
const uuidv1 = require('uuid/v1');
const mysql = require('mysql')
const fs = require('fs')
const pahtLib = require('path')

class WorkLog {
    constructor({type, name, pathParentId, userid, uuid, text = ''}) {
        this.type = type || 0
        this.name = name || `工作日志+${uuidv1()}`
        this.path_parent_id = pathParentId || ''
        this.userid = userid || ''
        this.uuid = uuid || uuidv1()
        this.text = text
    }
    // 提交
    async submit(query, rootPath) {
        const { type, name, path_parent_id, userid, uuid } = this;
        console.log('准备提交 1')
        console.log(
            JSON.stringify({
                type, name, path_parent_id, userid, uuid
            })
        )
        let sql = `INSERT into work_log set ?`;
        if (type === '0') {
            console.log('准备提交 2')
            try {
                await this.createFile(rootPath)
                console.log('准备提交 3')
            } catch (error) {
                console.log('准备提交 4')
                throw new Error('文件创建失败')
            }
        }
        return await query(sql, { type, name, path_parent_id, userid, uuid })
        
    }
    // 创建文件
    createFile (rootPath) {
        const { uuid } = this
        console.log('准备创建文件 1')
        return new Promise((resolve, reject) => {
            console.log('准备创建文件 2')
            fs.writeFile(pahtLib.resolve(rootPath, uuid), '', (error) => {
                if (error) {
                    reject(error)
                    console.log('准备创建文件 4')
                } else {
                    console.log('准备创建文件 3')
                    resolve(true)
                }
            })
        })
    }
    // 判断此文件是否已存在
    async isExist (query) {
        const { name, path_parent_id, userid } = this;
        let sql = mysql.format(
            `select * from work_log where userid=? and name=? and path_parent_id=?`,
            [userid, name, path_parent_id]
        )
        return await query(sql)
    }
    // 读取|写入 文件内容
    async readOrWriteFile (query, pathRoot, type = 'read') {
        const { text } = this
        let sql = mysql.format(`select * from work_log where uuid=?`, [this.uuid])
        let res = null
        try {
            res = await query(sql)
            if (res.results.length > 0) {
                let file = res.results[0]
                return new Promise((resolve, reject) => {
                    if (type === 'read') {
                        fs.readFile(pahtLib.resolve(pathRoot, file.uuid), 'utf-8', (err, data) => {
                            if (err) {
                                reject(err)
                            } else {
                                resolve({
                                    text: data,
                                    file
                                })
                            }
                        })
                    } else {
                        fs.writeFile(pahtLib.resolve(pathRoot, file.uuid), text, (err, data) => {
                            if (err) {
                                reject(err)
                            } else {
                                resolve({
                                    text: data,
                                    file
                                })
                            }
                        })
                    }
                })
            }
        } catch (error) {
            throw new Error(error)
        }
    }
}

module.exports = WorkLog;
